<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use think\Validate;

/**
 * D-地址相关接口
 * @ApiWeigh    (97)
 */
class Address extends Api {
	protected $noNeedLogin = [];
	protected $noNeedRight = ['*'];

	/**
	 * 地址列表
	 *
	 * @ApiTitle    (地址列表)
	 * @ApiSummary  (地址列表)
	 * @ApiMethod   (POST)
	 * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
	 *
	 * @ApiReturnParams   (name="per_page", type="object", description="每页数据")
	 * @ApiReturnParams   (name="current_page", type="object", description="当前页")
	 * @ApiReturnParams   (name="last_page", type="object", description="最后一页")
	 * @ApiReturnParams   (name="data", type="array", description="地址数组")
	 * @ApiReturnParams   (name="id", type="integer", required=true, description="地址id")
	 * @ApiReturnParams   (name="user_id", type="integer", required=true, description="用户id")
	 * @ApiReturnParams   (name="name", type="string", required=true, description="收件人姓名")
	 * @ApiReturnParams   (name="mobile", type="string", required=true, description="手机号码")
	 * @ApiReturnParams   (name="address_now", type="string", required=true, description="所在地区")
	 * @ApiReturnParams   (name="address", type="string", required=true, description="详细地址")
	 * @ApiReturnParams   (name="is_default", type="integer", required=true, description="是否默认地址:0=否,1=是")
	 *
	 * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码")
	 * @ApiReturnParams   (name="msg", type="string", required=true, description="提示语")
	 * @ApiReturnParams   (name="data", type="object", description="扩展数据返回")
	 */
	public function index() {
		$userId = $this->auth->id;

		$list = Db::name( 'user_address' )
			->where( ['user_id' => $userId] )
			->order( 'is_default', 'desc' )
			->order( 'id', 'desc' )
			->paginate( 15 );

		if ( $list->total() == 1 ) {
			//如果地址列表中仅存在一条地址数据 将这条数据修改为默认地址
			Db::name( 'user_address' )->where( 'user_id', $userId )->update( ['is_default' => 1] );
		}
		$this->success( '地址列表', $list );
	}

	/**
	 * 新增-编辑地址
	 *
	 * @ApiTitle    (新增-编辑地址)
	 * @ApiSummary  (新增-编辑地址)
	 * @ApiMethod   (POST)
	 * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
	 *
	 * @ApiParams   (name=id, type=integer, required=false, description="地址ID—修改时必须")
	 * @ApiParams   (name=name, type=string, required=true, description="收件人姓名")
	 * @ApiParams   (name=mobile, type=string, required=true, description="手机号码")
	 * @ApiParams   (name=address_now, type=string, required=true, description="所在地区")
	 * @ApiParams   (name=address, type=string, required=true, description="详细地址")
	 * @ApiParams   (name=is_default, type=integer, required=true, description="是否默认地址:0=否,1=是")
	 *
	 * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码:0=新增/保存失败,1=新增/编辑成功")
	 * @ApiReturnParams   (name="msg", type="string", required=true, description="提示语")
	 * @ApiReturnParams   (name="data", type="object", description="扩展数据返回")
	 */
	public function add_edit() {
		$rules    = [
			'name'        => 'require',
			'mobile'      => 'require|/^1\d{10}$/',
			'address_now' => 'require',
			'address'     => 'require',
			'is_default'  => 'require|in:0,1',
		];
		$message  = [
			'name.require'        => '收件人姓名不能为空',
			'mobile.require'      => '手机号码不能为空',
			'mobile./^1\d{10}$/'  => '请输入正确的手机号码',
			'address_now.require' => '所在地区不能为空',
			'address.require'     => '详细地址不能为空',
			'is_default.require'  => '是否默认地址不能为空',
			'is_default.in'       => '是否默认地址参数错误,请输入0或1',
		];
		$validate = new Validate( $rules, $message );

		$param = $this->request->param();
		if ( !$validate->check( $param ) ) {
			$this->error( $validate->getError() );
		}
		$userId = $this->auth->id;
		if ( empty( $param['id'] ) ) {
			//新增地址
			//新地址数据
			$data = [
				'user_id'     => $userId,
				'name'        => $param['name'],
				'mobile'      => $param['mobile'],
				'address_now' => $param['address_now'],
				'address'     => $param['address'],
				'is_default'  => $param['is_default'],
				'createtime'  => time(),
			];
			$find = Db::name( 'user_address' )->where( $data )->find();
			if ( $find ) {
				$this->error( '该地址信息已存在!' );
			}
			if ( $param['is_default'] == 1 ) {
				//若新增的地址设置为默认地址,将其他该用户的地址取消默认地址
				Db::name( 'user_address' )->where( 'user_id', $userId )->update( ['is_default' => 0] );
			}
			Db::name( 'user_address' )->insert( $data );
			$this->success( '添加成功' );
		} else {
			//编辑地址
			$find = Db::name( 'user_address' )->where( ['id' => $param['id']] )->find();
			if ( empty( $find ) ) {
				$this->error( '地址不存在' );
			}
			//编辑地址数据
			$data = [
				'name'        => $param['name'],
				'mobile'      => $param['mobile'],
				'address_now' => $param['address_now'],
				'address'     => $param['address'],
				'is_default'  => $param['is_default'],
				'updatetime'  => time(),
			];
			if ( $param['is_default'] == 1 ) {
				//若编辑的地址设置为默认地址,将其他该用户的地址取消默认地址
				Db::name( 'user_address' )->where( 'user_id', $userId )->update( ['is_default' => 0] );
			}
			//保存
			Db::name( 'user_address' )->where( ['id' => $param['id']] )->update( $data );
			$this->success( '修改成功' );
		}

	}

	/**
	 * 地址详情
	 *
	 * @ApiTitle    (地址详情)
	 * @ApiSummary  (地址详情)
	 * @ApiMethod   (POST)
	 * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
	 *
	 * @ApiParams   (name="id", type="integer", required=true, description="地址ID")
	 *
	 * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码")
	 * @ApiReturnParams   (name="msg", type="string", required=true, description="提示语")
	 * @ApiReturnParams   (name="data", type="object", description="数据返回")
	 * @ApiReturnParams   (name="id", type="integer", required=true, description="地址id")
	 * @ApiReturnParams   (name="user_id", type="integer", required=true, description="用户id")
	 * @ApiReturnParams   (name="name", type="string", required=true, description="收件人姓名")
	 * @ApiReturnParams   (name="mobile", type="string", required=true, description="手机号码")
	 * @ApiReturnParams   (name="address_now", type="string", required=true, description="所在地区")
	 * @ApiReturnParams   (name="address", type="string", required=true, description="详细地址")
	 * @ApiReturnParams   (name="is_default", type="integer", required=true, description="是否默认地址:0=否,1=是")
	 */
	public function detail() {
		$rules    = [
			'id' => 'require',
		];
		$message  = [
			'id.require' => '地址不能为空',
		];
		$validate = new Validate( $rules, $message );

		$param = $this->request->param();
		if ( !$validate->check( $param ) ) {
			$this->error( $validate->getError() );
		}

		$info = Db::name( 'user_address' )->where( ['id' => $param['id']] )->find();
		$this->success( '地址详情', $info );

	}

	/**
	 * 删除地址
	 *
	 * @ApiTitle    (删除地址)
	 * @ApiSummary  (删除地址)
	 * @ApiMethod   (POST)
	 * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
	 *
	 * @ApiParams   (name=ids, type=string, required=true, description="地址ID，多个以英文逗号隔开")
	 *
	 * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码")
	 * @ApiReturnParams   (name="msg", type="string", required=true, description="提示语")
	 * @ApiReturnParams   (name="data", type="object", description="扩展数据返回")
	 */
	public function del() {
		$rules    = [
			'ids' => 'require',
		];
		$message  = [
			'ids.require' => '请选择需要删除的地址',
		];
		$validate = new Validate( $rules, $message );

		$param = $this->request->param();
		if ( !$validate->check( $param ) ) {
			$this->error( $validate->getError() );
		}
		//删除前：该用户剩下一条地址信息后  不可删除
		$address_num = Db::name( 'user_address' )->where( 'user_id', $this->auth->id )->count();
		if ( $address_num == 1 ) {
			$this->error( '不可删除最后一条地址信息!' );
		}
		//删除中：删除地址信息
		$row = Db::name( 'user_address' )->where( ['id' => ['in', $param['ids']]] )->delete();
		if ( $row ) {
			//删除完：将最后一条地址信息更改为默认地址
			$address_num_two = Db::name( 'user_address' )->where( 'user_id', $this->auth->id )->count();
			if ( $address_num_two == 1 ) {
				Db::name( 'user_address' )->where( 'user_id', $this->auth->id )->update( ['is_default' => 1] );
			}
			$this->success( '删除成功' );
		} else {
			$this->error( '删除失败' );
		}
	}

//    /**
//     * @ApiTitle    (地址列表)
//     * @ApiSummary  (地址列表)
//     * @ApiMethod (POST)
//     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
//     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码")
//     * @ApiReturnParams   (name="msg", type="string", required=true, description="提示语")
//     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回")
//     * @ApiReturn   ({
//    "code":"状态码",
//    "msg": "提示消息",
//    "data": [
//    {
//    "id": "地址ID",
//    "name": "姓名",
//    "mobile": "联系方式",
//    "address": "地址",
//    "is_default": "是否默认地址:0=否,1=是"
//    }
//    ]
//    })
//     */
//    public function index()
//    {
//        $userId = $this->auth->id;
//        $list = Db::name('user_address')->where(['user_id' => $userId])->order('is_default', 'desc')->order('id', 'desc')->select();
//        $this->success('地址列表', $list);
//    }
//
//    /**
//     * @ApiTitle    (设置地址)
//     * @ApiSummary  (设置地址)
//     * @ApiMethod (POST)
//     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
//     *
//     * @ApiParams   (name=id, type=integer, required=false, description="地址ID—修改时必须")
//     * @ApiParams   (name=name, type=string, required=true, description="姓名")
//     * @ApiParams   (name=mobile, type=string, required=true, description="联系方式")
//     * @ApiParams   (name=address, type=string, required=true, description="地址")
//     *
//     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码")
//     * @ApiReturnParams   (name="msg", type="string", required=true, description="提示语")
//     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回")
//     * @ApiReturn   ({
//    "code":"状态码",
//    "msg": "提示消息"
//    })
//     */
//    public function add()
//    {
//        $rules = [
//            'name' => 'require',
//            'mobile' => 'require|mobile',
//            'address' => 'require',
//        ];
//        $message = [
//            'name.require' => '姓名不能为空',
//            'mobile.require' => '联系方式不能为空',
//            'mobile.mobile' => '请输入正确的手机号',
//            'address.require' => '地址不能为空',
//        ];
//        $validate = new Validate($rules, $message);
//
//        $param = $this->request->param();
//        if (!$validate->check($param)) {
//            $this->error($validate->getError());
//        }
//
//        if (empty($param['id'])) {
//        	//新增地址
//            $userId = $this->auth->id;
//            $find = Db::name('user_address')->where(['user_id' => $userId])->find();
//            //新地址数据
//            $data = [
//            	'user_id' => $userId,
//	            'name' => $param['name'],
//	            'mobile' => $param['mobile'],
//	            'address' => $param['address']
//            ];
//            if (empty($find)) {
//                $data['is_default'] = 1;
//            }
//            Db::name('user_address')->insert($data);
//            $this->success('添加成功');
//        } else {
//        	//编辑地址
//            $find = Db::name('user_address')->where(['id' => $param['id']])->find();
//            if(empty($find)){
//                $this->error('地址不存在');
//            }
//            //编辑地址数据
//            $data = [
//            	'name' => $param['name'],
//	            'mobile' => $param['mobile'],
//	            'address' => $param['address']
//            ];
//            Db::name('user_address')->where(['id' => $param['id']])->update($data);
//            $this->success('修改成功');
//        }
//
//    }
//
//    /**
//     * @ApiTitle    (地址详情)
//     * @ApiSummary  (地址详情)
//     * @ApiMethod (POST)
//     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
//     * @ApiParams   (name="id", type="integer", required=true, description="地址ID")
//     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码")
//     * @ApiReturnParams   (name="msg", type="string", required=true, description="提示语")
//     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回")
//     * @ApiReturn   ({
//    "code":"状态码",
//    "msg": "提示消息",
//    "data": {
//    "id": "地址ID",
//    "name": "姓名",
//    "mobile": "联系方式",
//    "address": "地址",
//    "is_default": "是否默认地址:0=否,1=是"
//    }
//    })
//     */
//    public function detail()
//    {
//        $rules = [
//            'id' => 'require',
//        ];
//        $message = [
//            'id.require' => '地址不能为空',
//        ];
//        $validate = new Validate($rules, $message);
//
//        $param = $this->request->param();
//        if (!$validate->check($param)) {
//            $this->error($validate->getError());
//        }
//
//        $info = Db::name('user_address')->where(['id' => $param['id']])->find();
//        $this->success('修改成功',$info);
//
//    }
//
//    /**
//     * @ApiTitle    (删除地址)
//     * @ApiSummary  (删除地址)
//     * @ApiMethod (POST)
//     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
//     * @ApiParams   (name=ids, type=string, required=true, description="地址ID，多个以英文逗号隔开")
//     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码")
//     * @ApiReturnParams   (name="msg", type="string", required=true, description="提示语")
//     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回")
//     * @ApiReturn   ({
//    "code":"状态码",
//    "msg": "提示消息"
//    })
//     */
//    public function del()
//    {
//        $rules = [
//            'ids' => 'require',
//        ];
//        $message = [
//            'ids.require' => '请选择需要删除的地址',
//        ];
//        $validate = new Validate($rules, $message);
//
//        $param = $this->request->param();
//        if (!$validate->check($param)) {
//            $this->error($validate->getError());
//        }
//        $row = Db::name('user_address')->where(['id' => ['in', $param['ids']]])->delete();
//        if ($row) {
//            $this->success('删除成功');
//        } else {
//            $this->error('删除失败');
//        }
//    }

}
